package com.mcp.weather.config;

/**
 * 配置管理类，从环境变量读取配置
 */
public class Config {
    private static final String DEFAULT_BASE_URL = "https://restapi.amap.com";
    private static final int DEFAULT_TIMEOUT_MS = 5000;
    private static final long DEFAULT_CACHE_TTL_BASE_MS = 60000L; // 60秒
    private static final long DEFAULT_CACHE_TTL_ALL_MS = 600000L; // 600秒

    private final String amapKey;
    private final String amapBaseUrl;
    private final int timeoutMs;
    private final long cacheTtlBaseMs;
    private final long cacheTtlAllMs;
    private final Integer httpPort;

    public Config() {
        this.amapKey = System.getenv("AMAP_KEY");
        this.amapBaseUrl = System.getenv().getOrDefault("AMAP_BASE_URL", DEFAULT_BASE_URL);
        this.timeoutMs = parseIntEnv("TIMEOUT_MS", DEFAULT_TIMEOUT_MS);
        this.cacheTtlBaseMs = parseLongEnv("CACHE_TTL_BASE_MS", DEFAULT_CACHE_TTL_BASE_MS);
        this.cacheTtlAllMs = parseLongEnv("CACHE_TTL_ALL_MS", DEFAULT_CACHE_TTL_ALL_MS);
        String httpPortStr = System.getenv("HTTP_PORT");
        this.httpPort = httpPortStr != null && !httpPortStr.isEmpty() ? parseIntEnv("HTTP_PORT", null) : null;
    }

    private int parseIntEnv(String key, Integer defaultValue) {
        String value = System.getenv(key);
        if (value == null || value.isEmpty()) {
            return defaultValue != null ? defaultValue : 0;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return defaultValue != null ? defaultValue : 0;
        }
    }

    private long parseLongEnv(String key, long defaultValue) {
        String value = System.getenv(key);
        if (value == null || value.isEmpty()) {
            return defaultValue;
        }
        try {
            return Long.parseLong(value);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    public String getAmapKey() {
        return amapKey;
    }

    public String getAmapBaseUrl() {
        return amapBaseUrl;
    }

    public int getTimeoutMs() {
        return timeoutMs;
    }

    public long getCacheTtlBaseMs() {
        return cacheTtlBaseMs;
    }

    public long getCacheTtlAllMs() {
        return cacheTtlAllMs;
    }

    public Integer getHttpPort() {
        return httpPort;
    }

    public boolean hasAmapKey() {
        return amapKey != null && !amapKey.isEmpty();
    }
}

